package org.gl.training.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.gl.training.model.UserRegistry;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet(name="RegisterServlet", urlPatterns="/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegisterServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String pageUsername = request.getParameter("username");
		String pagePassword = request.getParameter("pwd");
		String pageConfirmPassword = request.getParameter("confirm_pwd");

		if (StringUtils.isBlank(pageUsername)) {
			sendError(request, response, "Username is empty");
		} else if (StringUtils.isBlank(pagePassword)) {
			sendError(request, response, "Password is empty");
		} else if (StringUtils.isBlank(pageConfirmPassword)) {
			sendError(request, response, "ConfirmPassword is empty");
		} else if (!pagePassword.equals(pageConfirmPassword)) {
			sendError(request, response, "Passwords don't match");
		} else if (UserRegistry.getUserPassword(pageUsername) != null) {
			sendError(request, response, "Username is already registered");
		} else {
			String md5Password = DigestUtils.md5Hex(pagePassword);
			UserRegistry.addUser(pageUsername, md5Password);
			sendSuccess(request, response, "User registered successfully!");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	public void sendError(HttpServletRequest request,
			HttpServletResponse response, String errorMessage)
			throws ServletException, IOException {
		request.setAttribute("message", errorMessage);
		request.getRequestDispatcher("/jsp/error.jsp").forward(request,
				response);
	}

	public void sendSuccess(HttpServletRequest request,
			HttpServletResponse response, String successMessage)
			throws ServletException, IOException {
		request.setAttribute("message", successMessage);
		request.getRequestDispatcher("/jsp/success.jsp").forward(request,
				response);
	}
}
